package cn.com.oceansoft.business.os.api.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


/**
 * Controll层公用方法
 * 
 * @author Administrator
 * 
 */
public class RequestUtils {

	final private static int maxsizefj = 500000;
	
	/**
	 * 将request中的对象映射到map
	 * 
	 */
	public static Map<String, String> buildParamsByNamesFromRequest(
			HttpServletRequest request) {
		Map<?, ?> mp = request.getParameterMap(); // 获取客户端传递过来的所有参数
		@SuppressWarnings("unchecked")
		Set<String> keySet = (Set<String>) mp.keySet();
		HashMap<String, String> result = new HashMap<String, String>();
		for (String name : keySet) {
			String paramName = name;
			String paramValue = null;
			if (name.indexOf("|") > 0) {
				String[] nameValue = name.split("[|]");
				paramName = nameValue[0];
				paramValue = nameValue[1];
			}
			String nameObject = request.getParameter(paramName);
				if (StringUtils.hasText(nameObject)) {
					result.put(paramName, nameObject.trim());
				} else {
					if (paramValue != null)
						result.put(paramName, paramValue.trim());
				}

		}
		return result;
	}

	public static JSONObject map2Json(Map<String, String> m)
	{
		JSONObject json = new JSONObject();
		Set<String> keySet  = m.keySet();
		for (String k : keySet) {
			json.put(k, m.get(k));
		}
		return json;
	}
	
	public static JSONObject buildParamsByNamesFromRequest4JSON(
			HttpServletRequest request) {
		Map<?, ?> mp = request.getParameterMap(); // 获取客户端传递过来的所有参数
		JSONObject json = new JSONObject();
		@SuppressWarnings("unchecked")
		Set<String> keySet = (Set<String>) mp.keySet();
		for (String name : keySet) {
			String paramName = name;
			String paramValue = null;
			if (name.indexOf("|") > 0) {
				String[] nameValue = name.split("[|]");
				paramName = nameValue[0];
				paramValue = nameValue[1];
			}
			String nameObject = request.getParameter(paramName);
				if (StringUtils.hasText(nameObject)) {
					json.put(paramName, nameObject.trim());
				} else {
					if (paramValue != null)
						json.put(paramName, paramValue.trim());
				}

		}
		return json;
	}
	
}
